package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingBloodOxygen;
import com.ruoyi.ring.domain.dto.RingBloodOxygenAddDTO;
import com.ruoyi.ring.service.IRingBloodOxygenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 血氧 （APP）
 */
@Slf4j
@RestController
@RequestMapping("/ring/app/ring_blood_oxygen")
public class AppBloodOxygenController extends BaseController
{
    @Resource
    private IRingBloodOxygenService ringBloodOxygenService;
    /**
     * 新增血氧上报-app
     */
    @PostMapping("/add-blood-oxygen")
    public AjaxResult addBloodOxygen(@RequestBody RingBloodOxygenAddDTO addDTO) {
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingBloodOxygenAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingBloodOxygen bloodOxygen = ringBloodOxygenService.selectOneRingBloodOxygen(Builder.of(RingBloodOxygen::new).
                        with(RingBloodOxygen::setDeviceSn,deviceSn).
                        with(RingBloodOxygen::setDailyValue,dailyValue).build());
                RingBloodOxygen ringBloodOxygen = Convert.convert(RingBloodOxygen.class,stressDTO);
                if(bloodOxygen != null){
                    ringBloodOxygen.setId(bloodOxygen.getId());
                    ringBloodOxygen.setDeviceSn(deviceSn);
                    ringBloodOxygenService.updateRingBloodOxygen(ringBloodOxygen);
                }else {
                    ringBloodOxygen.setDeviceSn(deviceSn);
                    ringBloodOxygenService.insertRingBloodOxygen(ringBloodOxygen);
                }
            });

            return AjaxResult.success();
        }catch (Exception e){
            throw new RuntimeException("新增血氧上报失败！");
        }

    }
}
